<?php
namespace app\api\forms;

use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Password;

use Phalcon\Mvc\Model;
use Phalcon\Validation\Validator\Callback;
use Phalcon\Validation\Validator\PresenceOf;
use app\models\Admin;

class LoginForm extends FormBase
{
    public $username;

    public $password;

    protected $admin;

    public function getAdmin()
    {
        return $this->admin;
    }

    public function initialize()
    {
        $this->setEntity($this);

        $username = new Text("username");
        $username->addValidator(new PresenceOf(['message'=>'用户名不能为空']));

        $password = new Password("password");
        $password->addValidator(new PresenceOf(['message'=>'密码不能为空','cancelOnFail'=>true]));
        $password->addValidator(new Callback([
            'callback'=>function($data){
                $currentModel = Admin::findFirst([
                    'username = :username: and password = :password:',
                    'bind'=>[
                        'username'=>$data['username'],
                        'password'=>$data['password'],
                    ]
                ]);
                $this->admin = $currentModel;
                //var_dump($currentModel);

               return $currentModel?true:false;
            },
            'message'=>'用户名或密码错误',
        ]));

        $this->add($username);
        $this->add($password);
    }
}
